package MeteoCal.bean;

import MeteoCal.manager.InvitationManager;
import MeteoCal.manager.UserManager;
import MeteoCal.entity.Invitation;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @authors Guttadoro, Iommazzo, Saullo
 */
@ManagedBean(name="invitationBean")
@SessionScoped
public class InvitationBean implements Serializable{

    @EJB
    UserManager um;
    @EJB
    InvitationManager im;
    
    private List<Invitation> receivedin = new ArrayList<>();
    private List<List<Invitation>> sentin = new ArrayList<>();

    public List<List<Invitation>> getSentin() {
        return sentin;
    }

    public void setSentin(List<List<Invitation>> sentin) {
        this.sentin = sentin;
    }

    public String retriveInvitation() {
        System.err.println(um.getLoggedUser());
        receivedin = im.getInvitationsReceived(um.getLoggedUser().getEmail());
        sentin = im.getInvitationsSent(um.getLoggedUser());
        return "invitation?faces-redirect=true";
    }
    
    public List<Invitation> getReceivedin() {
        return receivedin;
    }
    
    public void setReceivedin(List<Invitation> receivedin) {
        this.receivedin = receivedin;
    }
    
    
  
    public int sizer(){
        return receivedin.size();
    }
    
    public int sizes(){
        
        int i = 0;
        for (List<Invitation> l: sentin)
            i += l.size();
        return i;
    }
    
    public String getName(List<Invitation> list){
        return list.get(0).getEvent().getName();
    }
    
    public String getDate_Hour(List<Invitation> list){
       Date d = list.get(0).getEvent().getDateBegin();
       Date h = list.get(0).getEvent().getHourBegin();
       
       return d.getDate()+"/"+(d.getMonth()+1)+"/"+(d.getYear()+1900)+", "+h.getHours()+"h "+h.getMinutes()+"m";
    }

    public void updateInvitation() throws Exception{
        
        
        if(!im.update(receivedin)){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning! Some events have not been added due to overlapping with other existing events in your calendar.", "Check your schedule and reply again to invitations."));
        }
        else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Successful!", "All your modifications have been taken into account."));

        }
        
        //setReceivedin(im.getInvitationsReceived(um.getLoggedUser().getEmail()));
        //receivedin.clear();
        //sentin.clear();
                
    }
}